import React, { useEffect, useRef, useState } from 'react'
import { Button, Col, Form, Input, Modal } from 'antd'
import useSocket from '../../hooks/useSockect'

const iconText = [
    '😀',
    '😃',
    '😄',
    '😁',
    '😆',
    '😅',
    '😂',
    '🤣',
    '😊',
    '😇',
    '🙂',
    '🙃',
    '😉',
    '😭',
]

function OrderAdd() {
    const user_id = '123'
    const [form] = Form.useForm()

    const connetion = useSocket(user_id)
    const [list, setList] = useState([])
    const wsRef = useRef(null)
    const divRef = useRef(null)

    const createFN = () => {
        wsRef.current = connetion()

        wsRef.current.onopen = () => {
            console.log('连接成功')
            // ws.send(  '{"type":"getChatList"}' )
            wsRef.current.send(JSON.stringify({ type: 'getChatList' }))
            haedbeat(); // 连接成功在取，发送心跳检测
        }

        wsRef.current.onmessage = (e) => {
            const { type, data } = JSON.parse(e.data)

            console.log(type, data)
            if (type === 'getChatList') {
                setList(data)
                setTimeout(() => {
                    divRef.current.scrollTop = 9999999;
                }, 0);
            }
            else if( type === 'addMessage' ) {
                wsRef.current.send(JSON.stringify({ type: 'getChatList' }))
            }
            else if( type === 'heartbeat' ) {
                localStorage.setItem('heartbeat', Date.now())
            }
        }
    }


    const head1 = useRef(null) 
    const head2 = useRef(null)

    const haedbeat = () => {
      head1.current = setInterval(() => {
        wsRef.current.send(JSON.stringify({type: "heartbeat"}))
      }, 1000)

      head2.current = setInterval(() => {
        const now = Date.now()
        const heartbeat = localStorage.getItem('heartbeat')

        if(now - heartbeat > 5000) {
          wsRef.current.close()
          createFN()
        }

      }, 10000)
    }
    // 心跳检测要在，组件卸载的时候销毁定时器, 和关闭聊天的socket连接
    useEffect(() => {
        return () => {
           clearInterval(head1.current)
           clearInterval(head2.current)
           wsRef.current.close()
        }
    }, [])

    useEffect(() => {
        createFN()
    }, [])

    const onFinish = (values) => {
        if(values.text) {
            // 有值，发送数据
            wsRef.current.send(  JSON.stringify({type: "addMessage", data: { message: values.text, type:'text' } })  )
            form.resetFields()
        }else {
            Modal.error({
                title:'请输入内容'
            })
        }
    }
    return (
        <div
            style={{
                display: 'flex',
                flexDirection: 'column',
                height: 500,
                gap: 20,
            }}
        >
            <div style={{ flex: 1, overflowY: 'auto' }} ref={divRef}>
                {list.map((item) => {
                    if (item.user_id === user_id) {
                        return (
                            <div
                                key={item.id}
                                style={{
                                    display: 'flex',
                                    gap: 10,
                                    flexDirection: 'row-reverse',
                                }}
                            >
                                <img
                                    style={{
                                        width: 50,
                                        height: 50,
                                        borderRadius: '50%',
                                    }}
                                    src={item.other_avatar}
                                    alt=""
                                />
                                <p
                                    style={{
                                        background: '#3fbdfcff',
                                        maxWidth: '70%',
                                        padding: 10,
                                        borderRadius: 10,
                                    }}
                                >
                                    {item.message}
                                </p>
                            </div>
                        )
                    }
                    return (
                        <div key={item.id} style={{ display: 'flex', gap: 10 }}>
                            <img
                                style={{
                                    width: 50,
                                    height: 50,
                                    borderRadius: '50%',
                                }}
                                src={item.user_avatar}
                                alt=""
                            />
                            <p
                                style={{
                                    background: '#aaa',
                                    maxWidth: '70%',
                                    padding: 10,
                                    borderRadius: 10,
                                }}
                            >
                                {item.message}
                            </p>
                        </div>
                    )
                })}
            </div>
            <div style={{ height: 80, background: '#fff' }}>
                <Form
                    form={form}
                    onFinish={onFinish}
                    layout="inline"
                    style={{ display: 'flex', justifyContent: 'space-between' }}
                >
                    <Form.Item name="text" style={{ flex: '1' }}>
                        <Input placeholder="请输入内容" />
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit">发送</Button>
                    </Form.Item>
                </Form>
                <div>
                    {iconText.map((v) => {
                        return (
                            <span key={v} style={{ padding: 5 }} onClick={() => {
                                wsRef.current.send(  JSON.stringify({type: "addMessage", data: { message: v, type:'text' } })  )
                            }}>
                                {v}
                            </span>
                        )
                    })}
                </div>
            </div>
        </div>
    )
}

export default OrderAdd
